package com.sugon.controller.spare;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.sugon.annotation.AutoLog;
import com.sugon.annotation.NonBusinessParamValid;
import com.sugon.entity.MaterialRecordEntity;
import com.sugon.entity.SpareStorePosEntity;
import com.sugon.entity.StoreHouseEntity;
import com.sugon.modules.base.consts.BusModule;
import com.sugon.modules.sparepart.model.vo.SparePartStorePosExchangeParamVO;
import com.sugon.modules.sparepart.service.ISparepartManager;
import com.sugon.modules.sparepart.service.ISparepartStoreManager;
import com.sugon.service.MaterialRecordService;
import com.sugon.service.SpareDevService;
import com.sugon.service.SpareStorePosService;
import com.sugon.service.StoreHouseService;
import com.sugon.utils.PageUtils;
import com.sugon.utils.Query;
import com.sugon.utils.R;
import com.sugon.utils.RRException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 备件仓库位置关联 用于存储备件位置以及数量Controller
 *
 * @author sugon
 * @date 2020-03-09 11:31:06
 */
@Controller
@RequestMapping("sparestorepos")
public class SpareStorePosController {

    @Autowired
    private SpareStorePosService spareStorePosService;
    @Autowired
    private ISparepartStoreManager sparepartStoreManager;
    @Autowired
    private ISparepartManager sparepartManager;
    @Autowired
    private SpareDevService spareDevService;
    @Resource
    private StoreHouseService storeHouseService;
    @Autowired
    private MaterialRecordService materialRecordService;


    /**
     * 查看备件库存列表
     * 线边库库存：从领料明细中看
     * ERP库存：从备案库存中看
     *
     * @param params
     * @return
     * @throws Exception
     */
    @RequestMapping("/list")
    @ResponseBody
    public R list(@RequestParam Map<String, Object> params) throws Exception {
        /*
            如果条件中包含库房ID，那么需要判定下这个库房是线边库库房还是ERP库房
            然后根据库房类型判定是从领料明细差还是备件库存差
         */
        Integer storeType = 1;
        String storeId = MapUtil.getStr(params, "storeId");
        String deptId = null;
        if (StrUtil.isNotEmpty(storeId)) {
            // 校验库房是否存在
            StoreHouseEntity storeHouse = storeHouseService.queryObject(storeId);
            if (storeHouse == null) {
                return R.error("库房不存在，请确认！");
            }
            storeType = storeHouse.getStoreType();
            deptId = storeHouse.getWorkshop();
        }
        /*
            线边库库存：默认从线边库领料中查询
            ERP库存：默认从备件库存中查询
         */
        if (NumberUtil.equals(storeType, 2)) {
            // 默认只看当前车间的领料记录
            if (StrUtil.isNotEmpty(deptId)) {
                params.put("deptId", deptId);
            }
            // 只要是审批了的就可以
            params.put("isReplaceable", 1);
            // 只看线边库的
            params.put("materialType", 1);
            Query query = new Query(params);
            //查询列表数据
            List<MaterialRecordEntity> materialRecordList = materialRecordService.queryList(query);
            int total = materialRecordService.queryTotal(query);
            PageUtils pageUtil = new PageUtils(materialRecordList, total, query.getLimit(), query.getPage());
            return R.ok().put("page", pageUtil);
        } else {
            List<String> matchedSparepartIdList;
            // 只要是map中含有任意一个备件查询参数，那么需要查询关联
            Map<String, Object> filterParams = MapUtil.getAny(params, "partName", "spec", "partCode", "erpCode", "producor");
            if (MapUtil.isNotEmpty(filterParams)) {
                matchedSparepartIdList = spareDevService.getMatchedSparePartIdList(params);
                if (CollectionUtil.isEmpty(matchedSparepartIdList)) {
                    return R.ok().put("page", new PageUtils(new ArrayList<>(), 0, MapUtil.getInt(params, "limit"), MapUtil.getInt(params, "page")));
                } else {
                    // 如果根据搜索条件搜索出来的内容超过1000，提示筛选搜索
                    Assert.isTrue(matchedSparepartIdList.size() < 500, "匹配当前查询条件的记录数过多，请进一步细化查询条件！");
                    params.put("sparepartIdList", matchedSparepartIdList);
                }
            }
            return R.ok().put("page", sparepartManager.querySparePartsStock(params));
        }
    }

    /**
     * 查看信息
     */
    @RequestMapping("/info/{id}")
    @ResponseBody
    public R info(@PathVariable("id") String id) {
        SpareStorePosEntity spareStorePos = spareStorePosService.queryObject(id);

        return R.ok().put("spareStorePos", spareStorePos);
    }

    @NonBusinessParamValid
    @AutoLog(value = "备件移库", busModule = BusModule.SP_STOCK)
    @RequestMapping("/exchange")
    @RequiresPermissions("sparestorepos:exchange")
    @ResponseBody
    public R exchange(@Validated @RequestBody SparePartStorePosExchangeParamVO storePosExchangeParam, BindingResult bindingResult) {
        // 校验当前库位是否存在
        SpareStorePosEntity current = spareStorePosService.queryObject(storePosExchangeParam.getId());
        if (current == null) {
            return R.error("当前库位信息不存在！");
        }
        // 转移数不得大于当前库存数
        int exchangeNum = storePosExchangeParam.getExchangeNum();
        if (current.getStoreNum() < exchangeNum) {
            return R.error("转移数不得大于当前库存数！");
        }
        // 校验目标库位是否存在
        String targetId = storePosExchangeParam.getTargetId();
        String targetPosition = storePosExchangeParam.getTargetPostion();
        if (StrUtil.isEmpty(targetId) && StrUtil.isEmpty(targetPosition)) {
            return R.error("目标库位信息必填！");
        }
        SpareStorePosEntity target = null;
        if (StrUtil.isNotEmpty(targetId)) {
            // 转移库位和目标库位不得一样
            if (targetId.equals(storePosExchangeParam.getId())) {
                return R.error("移库操作时，当前库位和目标库位必须是不同库位！");
            }
            target = spareStorePosService.queryObject(storePosExchangeParam.getTargetId());
            if (target == null) {
                return R.error("目标库位信息不存在！");
            }
        } else if (StrUtil.isNotEmpty(targetPosition)) {
            String targetStoreId = storePosExchangeParam.getTargetStoreId();
            if (StrUtil.isEmpty(targetStoreId)) {
                return R.error("新增库位时，目标仓库必选！");
            }
            // 同一个仓库时，库位名称不得一样
            if (current.getStoreId().equals(targetStoreId)) {
                if (current.getPostion().equals(targetPosition)) {
                    return R.error("同一个仓库时，新增库位名称已存在，请确认！");
                }
            }
            String spareCode = storePosExchangeParam.getSpareCode();
            if (StrUtil.isEmpty(spareCode)) {
                return R.error("新增库位时，备件编码必选！");
            }
            // 根据库位编码创建一个
            target = spareStorePosService.queryByPosition(targetStoreId, targetPosition, spareCode);
            if (target == null) {
                target = new SpareStorePosEntity();
                target.setStoreId(targetStoreId);
                target.setPostion(targetPosition);
                target.setStoreNum(0);
                target.setSpareCode(spareCode);
                spareStorePosService.save(target);
            }
        } else {
            return R.error("目标库位信息必填！");
        }
        return sparepartStoreManager.exchangeStorePos(current, target, exchangeNum) ? R.ok() : R.error();
    }

    /**
     * 保存
     */
    @AutoLog(value = "保存", busModule = BusModule.SP_STOCK)
    @RequestMapping("/save")
    @RequiresPermissions("sparestorepos:save")
    @ResponseBody
    public R save(@RequestBody SpareStorePosEntity spareStorePos) {
        spareStorePosService.save(spareStorePos);

        return R.ok();
    }

    /**
     * 修改
     */
    @AutoLog(value = "修改", busModule = BusModule.SP_STOCK)
    @RequestMapping("/update")
    @RequiresPermissions("sparestorepos:update")
    @ResponseBody
    public R update(@RequestBody SpareStorePosEntity spareStorePos) {
        spareStorePosService.update(spareStorePos);

        return R.ok();
    }

    /**
     * 删除
     */
    @AutoLog(value = "删除", busModule = BusModule.SP_STOCK)
    @RequestMapping("/delete")
    @RequiresPermissions("sparestorepos:delete")
    @ResponseBody
    public R delete(@RequestBody String[] ids) {
        spareStorePosService.deleteBatch(ids);

        return R.ok();
    }

    /**
     * 查看所有列表
     */
    @RequestMapping("/queryAll")
    @ResponseBody
    public R queryAll(@RequestParam Map<String, Object> params) {

        List<SpareStorePosEntity> list = spareStorePosService.queryList(params);

        return R.ok().put("list", list);
    }

    /**
     * 当前位置是否存在
     */
    @RequestMapping("/queryIsHave")
    @ResponseBody
    public R queryIsHave(@RequestParam Map<String, Object> params) {
        int flag = 0;
        List<SpareStorePosEntity> list = spareStorePosService.queryList(params);
        if (list.size() > 0) {
            flag = 1;
        }
        return R.ok().put("isHave", flag);
    }

    /**
     * excel导入
     */
    @AutoLog(value = "导入", busModule = BusModule.SP_STOCK)
    @RequestMapping("/import")
    @RequiresPermissions("sparestorepos:import")
    @ResponseBody
    public R importE(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }
        // 执行导入
        int count = spareStorePosService.importE(file);
        return R.ok("成功导入" + count + "条数据");
    }

}
